/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.epam.javatanf2013.web.examples.filters;

import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Istvan_Monori
 */
public class RedirectFilterExample implements Filter{
    private FilterConfig config;
    private ServletContext context;
    @Override
    public void init(FilterConfig fc) throws ServletException {
        this.config  = fc;
        this.context = fc.getServletContext();
        this.context.log("RedirectFilterExample initialized");
    }
    
    public FilterConfig getConfig() {
        return this.config;
    }
    
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Enumeration<String> en = getConfig().getInitParameterNames();
        String uri = request.getRequestURI();
        this.context.log("Requested Resource::"+uri);        
        while(en.hasMoreElements()) {
            String element = en.nextElement();
            if (request.getRequestURI().equals(request.getContextPath()+element)) {
                String value = getConfig().getInitParameter(element);
                response.sendRedirect(request.getContextPath()+value);
                this.context.log("Auto redirect::"+value);        
                return;
            }
        }
        fc.doFilter(req, resp);
    }

    @Override
    public void destroy() {
        
    }
    
}
